/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/
#pragma once
#include <netinet/in.h>
#include <string>
#include <memory>
#include <gflags/gflags.h>
#include "net/net_interface.h"

namespace air {
namespace net {

DECLARE_string(net_udp_server_url);
DECLARE_string(net_udp_local_url);

class UdpImpl : public NetInterface {
 public:
  static std::shared_ptr<UdpImpl> GetInstance();

  int SetOption(NetOption opt, const std::string& val) override;

  int Connect() override;

  int Send(const std::string& dst, const std::string& data) override;

  int Recv(std::string* src, std::string* data) override;

 private:
  UdpImpl() = default;
  UdpImpl(const UdpImpl&) = delete;
  UdpImpl& operator=(const UdpImpl&) = delete;

  bool ParseUrl(const std::string& url, std::string* ip, std::string* port);
  bool BuildAddr(const std::string& url, struct sockaddr_in* addr);
  struct sockaddr_in local_addr_{ 0 };
  struct sockaddr_in target_addr_{ 0 };
  int fd_{ -1 };
  char buf_[8192]{ 0 };
};

}  // namespace net
}  // namespace air
